package cn.tedu.web.stm.Servlet;

import cn.tedu.web.stm.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        Object cun = session.getAttribute("cun");
        boolean isTrue = cun!=null && code!=null && cun.equals(code);
        if(!isTrue){
            PrintWriter writer = resp.getWriter();
            writer.write("验证码错误!");
            writer.flush();
            writer.close();
            return;
        }
        String sql = "SELECT * FROM `user` WHERE username = ? AND `password` = MD5(?)";
        Long id = JdbcUtils.select(sql, Long.class, username,password);
        if(id != null){
            session.setAttribute("UID",id);
            resp.sendRedirect("/Stm/index.jsp");
        }else {
            resp.sendRedirect("/Stm/login.jsp");
        }
//        String message =id !=null && id>0L ? "登陆成功!":"登录失败！";
//        PrintWriter writer = resp.getWriter();
//        writer.write(message);
//        writer.flush();
//        writer.close();
    }
}
